package com.tanhua.server.service;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.SoundApi;
import com.tanhua.dubbo.server.pojo.Sound;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.SoundUploadResult;
import com.tanhua.server.vo.SoundVo;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;


/**
 * @Author:
 * @Description:
 * @Date: Created in 11:43 2021/1/17
 * @ModifiedBy:
 */
@Service
public class SoundService {
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private SoundUploadService soundUploadService;

    @Reference(version = "1.0.0")
    private SoundApi soundApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 上传语音
     *
     * @param soundFile
     * @return
     */
    public Boolean sendSound(MultipartFile soundFile) {
        //获取token
        User user = UserThreadLocal.get();
        //创建语音对象
        Sound sound = new Sound();
        //给redis设置key
        String redisKey = "Voice_Send_" + user.getId();
        //设置value
        String value = this.redisTemplate.opsForValue().get(redisKey);
        //判断值为空
        if (StringUtils.isEmpty(value)) {
            //设置一天剩余次数为8次
            redisTemplate.opsForValue().set(redisKey, "8", Duration.ofDays(1));
        }
        //判断剩余次数是否小于0
        if (Integer.valueOf(redisTemplate.opsForValue().get(redisKey)) <= 0) {
            return null;
        }
        //获取用户id设置给userid
        sound.setUserId(user.getId());
        try {
            //上传声音文件
            SoundUploadResult soundUploadResult = this.soundUploadService.upload(soundFile);
            sound.setSoundUrl(soundUploadResult.getName());
            if (redisTemplate.hasKey(redisKey)) {
                this.redisTemplate.opsForValue().decrement(redisKey);
            }
            return this.soundApi.saveSound(sound);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 随机生成语音，保证不重复
     *
     * @param newList
     */
    private int RandomSound(List<Sound> newList, User user) {
        int index = RandomUtils.nextInt(0, newList.size() - 1);
        Sound sound = newList.get(index);
        String key = "Voice_Random_" + sound.getId() + user.getId();
        String value = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotEmpty(value)) {
            RandomSound(newList, user);
        }
        redisTemplate.opsForValue().set(key, "1");
        return index;
    }

    public SoundVo querySound() {
        //创建user对象
        User user = UserThreadLocal.get();
        //创建redis的ke与value
        String redisKey = "Voice_Get_" + user.getId();
        String value = this.redisTemplate.opsForValue().get(redisKey);
        //value为空则添加剩余次数为十;有一天的使用期限
        if (StringUtils.isEmpty(value)) {
            redisTemplate.opsForValue().set(redisKey, "10", Duration.ofDays(1));
            //redisTemplate.expire(redisKey,1, TimeUnit.DAYS);
        }
        //查询所有的语音文件存入集合
        List<Sound> list = soundApi.querySoundList(user.getId());
        //创建一个long的list集合
        List<Long> idList = new ArrayList<>();
        //循环将sound对象的userId存入idlist集合中
        for (Sound sound : list) {
            idList.add(sound.getUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper();
        queryWrapper.in("user_id", idList);
        //获取userinfo集合
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);
        List<SoundVo> newList = new ArrayList<>();

        for (Sound sound : list) {
            for (UserInfo userInfo : userInfos) {
                if (sound.getUserId() == userInfo.getUserId().longValue()) {
                    SoundVo soundVo = new SoundVo();
                    soundVo.setId(Integer.valueOf(sound.getUserId().toString()));
                    soundVo.setNickname(userInfo.getNickName());
                    soundVo.setAvatar(userInfo.getLogo());
                    soundVo.setAge(userInfo.getAge());
                    soundVo.setSoundUrl(sound.getSoundUrl());
                    soundVo.setRemainingTimes(Integer.valueOf(redisTemplate.opsForValue().get(redisKey)));
                    newList.add(soundVo);
                    break;
                }
            }
        }

        if (redisTemplate.hasKey(redisKey)) {
            this.redisTemplate.opsForValue().decrement(redisKey);
        }


        return newList.get(RandomSound(list, user));

    }
}

